using Digitalmes.Domain.Entities.Mes.Productions;

namespace Digitalmes.Application.Mes.Productions.WorkOrders.Commands;

/// <summary>
/// 工单创建命令。
/// </summary>
public sealed record CreateWorkOrderCommand(ProdWorkOrderDto WorkOrder) : IRequest<IResult<bool>>;

internal sealed class CreateWorkOrderCommandHandler(IRepository<ProdWorkOrder> repo) : IRequestHandler<CreateWorkOrderCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(CreateWorkOrderCommand request, CancellationToken cancellationToken)
    {
        // 检查单号不能重复
        if (await repo.IsAnyAsync(m => m.Wo == request.WorkOrder.Wo, cancellationToken))
        {
            return Result.Failure("工单单号已存在");
        }

        var workOrder = request.WorkOrder.Adapt<ProdWorkOrder>();
        workOrder.Status = WoStatusEnum.Draft;

        var ok = await repo.InsertAsync(workOrder, cancellationToken);
        return Result.From(ok);
    }
}
